package cn.com.stary1993.kite.captcha.support.behavior.secondary;

import cloud.tianai.captcha.validator.common.model.dto.ImageCaptchaTrack;
import cn.com.stary1993.kite.captcha.config.BehaviorImageCaptchaProperties.SecondaryVerificationProperties;
import cn.com.stary1993.kite.captcha.support.behavior.BehaviorImageCaptcha;
import cn.com.stary1993.kite.captcha.support.behavior.FilterBehaviorImageCaptcha;

import java.util.Collections;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 二次验证
 *
 * @author stary1993
 */
public class BehaviorImageCaptchaSecondaryVerification extends FilterBehaviorImageCaptcha {

	private SecondaryVerificationProperties prop;

	public BehaviorImageCaptchaSecondaryVerification(BehaviorImageCaptcha target,
			SecondaryVerificationProperties prop) {
		super(target);
		this.prop = prop;
	}

	@Override
	public boolean matching(String id, ImageCaptchaTrack imageCaptchaTrack) {
		boolean match = super.matching(id, imageCaptchaTrack);
		if (match) {
			// 如果匹配成功， 添加二次验证记录
			addSecondaryVerification(id, imageCaptchaTrack);
		}
		return match;
	}

	/**
	 * 二次缓存验证
	 * @param id id
	 * @return boolean
	 */
	public boolean secondaryVerification(String id) {
		Map<String, Object> cache = (Map<String, Object>) target.getCacheStore().getAndRemoveCache(getKey(id));
		return cache != null;
	}

	/**
	 * 添加二次缓存验证记录
	 * @param id id
	 * @param imageCaptchaTrack sliderCaptchaTrack
	 */
	protected void addSecondaryVerification(String id, ImageCaptchaTrack imageCaptchaTrack) {
		target.getCacheStore().setCache(getKey(id), Collections.emptyMap(), prop.getExpire(), TimeUnit.MILLISECONDS);
	}

	protected String getKey(String id) {
		return prop.getKeyPrefix().concat(":").concat(id);
	}

}
